//
//  FSProfileSearchController.m
//  WZSOA
//
//  Created by 刘沿 on 16/7/4.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSProfileSearchController.h"
#import "GDataDefines.h"

@interface FSProfileSearchController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic,assign)int currentPage; //当前页

@property (nonatomic,strong) NSMutableArray *KindArray;

@property (nonatomic,strong) UIView *view1;

@property (nonatomic,assign) NSInteger totalCounts;

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIButton *lastbtn;

@property (nonatomic,assign) NSInteger index;

@end

@implementation FSProfileSearchController

-(NSMutableArray *)dataArray{

    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
}

-(NSMutableArray *)KindArray{
    if (_KindArray == nil) {
        
        _KindArray = [NSMutableArray array];
    }

    return _KindArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 0;
    
    self.view.backgroundColor = [UIColor colorWithRed:188/255.0 green:193/255.0 blue:196/255.0 alpha:1];

    self.title = @"公文查询";
    //搜索框
    UISearchBar *search = [[UISearchBar alloc] init];
    search.delegate = self;
    search.searchBarStyle = UISearchBarStyleMinimal;
    search.placeholder = @"请输入搜索内容";
    search.layer.cornerRadius = 10;
    search.layer.masksToBounds = YES;
    
    search.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:search];
    
    [search mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(64);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@60);
        
    }];
//时间
    UIView *view1 = [[UIView alloc] init];

    self.view1 = view1;
    
    view1.backgroundColor = [UIColor colorWithRed:236/255.0 green:247/255.0 blue:250/255.0 alpha:1];
    
    [self.view addSubview:view1];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(search.mas_bottom).mas_offset(10);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.height.equalTo(@90);
    }];
    
//创建表格
    UITableView *tab = [[UITableView alloc] init];
    
    tab.delegate = self;
    
    tab.dataSource = self;
    
    self.tableView = tab;
    
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view1.mas_bottom);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-20);
    }];
    
    __weak typeof (self) weakSelf = self;
    
    [self.tableView addHeaderWithCallback:^{
        
        weakSelf.currentPage = 1;
        
        [weakSelf setKind];
        
    }];
    [self.tableView headerBeginRefreshing];
    
    [tab addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            
            [weakSelf loadMore:weakSelf.lastbtn];
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];
    
    
}

- (void)setKind{
    
    NSString *uesrId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userId":uesrId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

    [HttpTools requestWithURL:Kexcharchive arrays:array method:KgetFileYear success:^(id JSON) {
        
        NSArray *tempArray = JSON[@"data"];
        
        NSMutableArray *dictArray1 = [NSMutableArray array];
        
        for (NSDictionary *dict in tempArray) {
            
            [dictArray1 addObject:dict[@"name"]];
        }
        
        self.KindArray = dictArray1;
        
        if (self.index == 0) {
            
            [self setUpKind:self.KindArray];

        }
        
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
    } failure:^(NSError *error) {
        
    }];
    
}

//设置类型界面
- (void)setUpKind:(NSMutableArray *)arr{
    
    self.index ++;
    
    CGFloat ViewW = self.view.frame.size.width;
    
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 10;//用来控制button距离父视图的高
    
    for (int i = 0; i < arr.count; i ++) {
        
        //创建按钮
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                
        btn.tag = i;
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        
        //        [btn setTitle:[NSString stringWithFormat:@"[%@]",arr[i]] forState:UIControlStateNormal];
        
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        
        [btn addTarget:self action:@selector(btnClick2:) forControlEvents:UIControlEventTouchUpInside];
        
        if (btn.tag == 0) {
            
            self.lastbtn = btn;

            [self loadMore:btn];
            
            btn.selected = YES;
        }
        
        //计算大小
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(ViewW, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        
        btn.frame = CGRectMake(10 + w, h, length + 40 , 30);
        //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
        if(10 + w + length + 40 > ViewW){
            w = 0; //换行时将w置为0
            h = h + btn.frame.size.height + 10;//距离父视图也变化
            btn.frame = CGRectMake(10 + w, h, length + 40, 30);//重设button的frame
        }
        w = btn.frame.size.width + btn.frame.origin.x;
        
        [self.view1 addSubview:btn];
        
    }
    
    
}

- (void)btnClick2:(UIButton *)btn{
    self.currentPage = 1;
    //第一次点击的时候上一个按钮是直属单位
    
    btn.selected = YES;
    
    self.lastbtn.selected = NO;
    
    if (self.lastbtn == btn) {
        
        self.lastbtn.selected = YES;
        return;
    }
    
    [self.dataArray removeAllObjects];
    
    NSString *dbpath = [NSString stringWithFormat:@"weboa/files/files%@.nsf",btn.titleLabel.text];

    NSString *uesrId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userId":uesrId},@{@"dbpath":dbpath},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

    
    [HttpTools postWithURL:Kexcharchive arrays:array method:KarchiveFilePage success:^(id JSON) {
        
        if (self.currentPage == 1) {
            
            [self.dataArray removeAllObjects];
            
        }
        
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没最新数据哦"];
        }
        
        self.lastbtn = btn;

    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark-----加载更多
- (void)loadMore:(UIButton *)btn{
    
    NSString *dbpath = [NSString stringWithFormat:@"weboa/files/files%@.nsf",btn.titleLabel.text];
    
    NSString *uesrId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userId":uesrId},@{@"dbpath":dbpath},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:Kexcharchive arrays:array method:KarchiveFilePage success:^(id JSON) {
            
            [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
            self.currentPage++;
            if (self.dataArray.count ==0) {
                [self.view makeToast:@"暂时还没最新数据哦"];
            }
        self.lastbtn = btn;

        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
        } failure:^(NSError *error) {
            
            
        }];



}



#pragma mark-----解析服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel* model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    //获取根节点下的数据
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
    self.title = [NSString stringWithFormat:@"公文查询(%lu)",(unsigned long)self.totalCounts];
    
    return array;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *ReuseIdentifier = @"Cell";
    
    FSUpDoingReceiveCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier];
    if (cell == nil) {
        
        cell = [FSUpDoingReceiveCell UpDoingReceiveCell];
    }
    cell.receiveModel = self.dataArray[indexPath.row];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FSReceiveModel *model = self.dataArray[indexPath.row];
    
    CGFloat titleFloat = [FSHightTool heightbyString:model.title font:20 minsWidth:60];
    NSString *desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    
    CGFloat desfloat = [FSHightTool heightbyString:desstring font:14 minsWidth:60];
    
    return titleFloat + desfloat + 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FSReceiveModel * model = self.dataArray[indexPath.row];
    
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FSNewReceiveDetailController *vc = [story instantiateViewControllerWithIdentifier:@"NewDetailReceiveVC"];
    
    vc.type = ProfileSear;
    
    vc.fileId = model.fileId;
    
    vc.dbpath = [NSString stringWithFormat:@"weboa/files/files%@.nsf",self.lastbtn.titleLabel.text];
    
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma  mark -----搜索框代理
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    NSString *text = searchBar.text;
    
    FSSearchViewController *searchVC = [[FSSearchViewController alloc] init];
    
    searchVC.type = profileSearch;
    
    searchVC.text = text;
    
    NSString *dbpath = [NSString stringWithFormat:@"weboa/files/files%@.nsf",self.lastbtn.titleLabel.text];
    
    searchVC.debpath = dbpath;
    
    [self.navigationController pushViewController:searchVC animated:YES];
    
}


@end






















